package com.item.spring.jdbc.dao;

import com.item.spring.jdbc.entity.Employee;
import com.sun.org.apache.bcel.internal.generic.RET;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;
import java.util.Map;

public class EmployeeDao {
    private JdbcTemplate jdbcTemplate;

    public JdbcTemplate getJdbcTemplate() {
        return jdbcTemplate;
    }

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    /**
     * 根据id查找数据
     * queryForObject 返回单条数据
     *
     * @param eno
     * @return
     */
    public Employee findById(Integer eno) {
        String sql = "SELECT * FROM employee WHERE eno = ?";
        //查询单条数据  如果有多个条件，则  new Object[]{eno,eno2,eno3} 数组中的顺序对应着sql中问好的顺序
        Employee employee = jdbcTemplate.queryForObject(sql, new Object[]{eno}, new BeanPropertyRowMapper<Employee>(Employee.class));
        return employee;
    }

    /**
     * query 返回list
     *
     * @param depName
     * @return
     */
    public List<Employee> findByName(String depName) {
        String sql = "SELECT * FROM employee WHERE dname = ?";
        List<Employee> query = jdbcTemplate.query(sql, new Object[]{depName}, new BeanPropertyRowMapper<Employee>(Employee.class));
        return query;
    }

    /**
     * queryForList 返回map集合数据 ，当返回的字段名字是entity中没有的时候就使用这个
     * @param depName
     * @return
     */
    public List<Map<String, Object>> findMapByName(String depName) {
        String sql = "SELECT eno  enoAs,ename enameAs,salary salaryAs,dname  dnameAs FROM employee WHERE dname = ?";
        List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql, new Object[]{"depName"});
        return maps;
    }


    public void insert(Employee employee){
        String sql = "insert into employee(eno,ename,salary,dname,hiredate) values(?,?,?,?,?)";
        //利用update方法实现数据写入操作
        jdbcTemplate.update(sql,new Object[]{
                employee.getEno() , employee.getEname(),employee.getSalary(),employee.getDname() , employee.getHiredate()
        });
    }

    public int update(Employee employee){
        String sql = "UPDATE employee SET ename = ?, salary = ?, dname = ?, hiredate = ? WHERE eno = ?";
        int count = jdbcTemplate.update(sql, new Object[]{employee.getEname(), employee.getSalary(), employee.getDname(), employee.getHiredate(), employee.getEno()});
        return count;
    }

    public int delete(Integer eno){
        String sql = "delete from employee where eno = ?";
        return jdbcTemplate.update(sql, new Object[]{eno});
    }

}
